package uk.ac.cam.cl.android.jwdb;

import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import android.os.Handler;
import android.widget.Button;
import android.widget.TextView;

public class Level {
	public int time;
	Button button;
	int count;
	int score;
	int number;
	TextView scoreText;
	TextView timeText;
	Timer timer;
	LevelActivity activity;

	public Level(int time, Button button, int number, TextView scoreText,
			TextView levelText, TextView timeText, LevelActivity activity) {
		this.time = time;
		this.count = 0;
		this.button = button;
		this.number = number;
		levelText.setText(Integer.toString(number));
		this.score = Integer.parseInt((String) scoreText.getText());
		this.scoreText = scoreText;
		this.timeText = timeText;
		this.activity = activity;
	}

	public void startLevel() {

		nextAction();
		timer = new Timer();
		final Handler handler = new Handler();

		timer.scheduleAtFixedRate(new TimerTask() {
			public void run() {
				handler.post(new Runnable() {
					public void run() {
						decrementTime();
					}
				});
			}
		}, 0, 1000);
	}

	private void decrementTime() {
		time--;
		timeText.setText(Integer.toString(time));
		if (time < 0) {
			// TODO game over!
			timer.cancel();
			activity.gameOver(score);
		}
	}

	public void nextAction() {
		Random random = new Random();
		int r = random.nextInt(5);
		Action action;
		switch (r) {
		case 0:
			action = new TapIt();
			break;
		case 1:
			action = new ShakeIt();
			break;
		case 2:
			action = new DropIt();
			break;
		case 3:
			action = new LiftIt();
			break;
		case 4:
			action = new SwipeIt();
			break;
		default:
			action = new TapIt();
		}

		if (count == 0) {
			score -= 10;
		}
		count++;
		score += 10;
		scoreText.setText(Integer.toString(score));

		action.display(button, this);
		action.check();

	}
}
